#include "metermodel.h"
#include "../utils/logger.h"
#include <algorithm>

MeterModel::MeterModel(DeviceManager *deviceManager, QObject *parent)
    : QAbstractListModel(parent), m_deviceManager(deviceManager), m_filterMode(ShowAll), m_filterBusId(0)
{
    // 创建批量更新定时器（延迟100ms，合并多次更新）
    m_updateTimer = new QTimer(this);
    m_updateTimer->setSingleShot(true);
    m_updateTimer->setInterval(100);
    connect(m_updateTimer, &QTimer::timeout, this, &MeterModel::processPendingUpdates);

    // 连接设备管理器信号
    connect(m_deviceManager, &DeviceManager::deviceOnline, this, &MeterModel::onDeviceOnline);
    connect(m_deviceManager, &DeviceManager::deviceOffline, this, &MeterModel::onDeviceOffline);
    connect(m_deviceManager, &DeviceManager::totalCountChanged, this, &MeterModel::onTotalCountChanged);

    // 初始化数据
    updateFilteredMeters();

    Logger::instance()->log(LogLevel::Info, "MeterModel: 电表模型已初始化");
}

MeterModel::~MeterModel()
{
    Logger::instance()->log(LogLevel::Info, "MeterModel: 电表模型已销毁");
}

// 返回行数
int MeterModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
    {
        return 0;
    }

    return m_filteredMeters.size();
}

// 获取数据
QVariant MeterModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() < 0 || index.row() >= m_filteredMeters.size())
    {
        return QVariant();
    }

    Meter *meter = m_filteredMeters[index.row()];
    if (!meter)
    {
        return QVariant();
    }

    switch (role)
    {
    case MeterIdRole:
        return meter->meterId();
    case NameRole:
        return meter->name();
    case LocationRole:
        return meter->location();
    case BusIdRole:
        return meter->busId();
    case OnlineRole:
        return meter->isOnline();
    case UaRole:
        return meter->ua();
    case UbRole:
        return meter->ub();
    case UcRole:
        return meter->uc();
    case IaRole:
        return meter->ia();
    case IbRole:
        return meter->ib();
    case IcRole:
        return meter->ic();
    case AverageVoltageRole:
        return meter->averageVoltage();
    case AverageCurrentRole:
        return meter->averageCurrent();
    case TotalPowerRole:
        return meter->totalPower();
    case LastUpdateTimeRole:
        return meter->lastUpdateTime();
    case FailureCountRole:
        return meter->failureCount();
    case MeterObjectRole:
        return QVariant::fromValue(meter);
    default:
        return QVariant();
    }
}

// 角色名称
QHash<int, QByteArray> MeterModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[MeterIdRole] = "meterId";
    roles[NameRole] = "name";
    roles[LocationRole] = "location";
    roles[BusIdRole] = "busId";
    roles[OnlineRole] = "online";
    roles[UaRole] = "ua";
    roles[UbRole] = "ub";
    roles[UcRole] = "uc";
    roles[IaRole] = "ia";
    roles[IbRole] = "ib";
    roles[IcRole] = "ic";
    roles[AverageVoltageRole] = "averageVoltage";
    roles[AverageCurrentRole] = "averageCurrent";
    roles[TotalPowerRole] = "totalPower";
    roles[LastUpdateTimeRole] = "lastUpdateTime";
    roles[FailureCountRole] = "failureCount";
    roles[MeterObjectRole] = "meterObject";
    return roles;
}

// 设置过滤模式
void MeterModel::setFilterMode(FilterMode mode)
{
    if (m_filterMode != mode)
    {
        m_filterMode = mode;
        emit filterModeChanged();
        updateFilteredMeters();

        Logger::instance()->log(LogLevel::Debug,
                                QString("MeterModel: 过滤模式改变: %1").arg(mode));
    }
}

// 设置过滤总线ID
void MeterModel::setFilterBusId(int busId)
{
    if (m_filterBusId != busId)
    {
        m_filterBusId = busId;
        emit filterBusIdChanged();

        // 如果当前是按总线过滤模式，更新数据
        if (m_filterMode == ShowByBus)
        {
            updateFilteredMeters();
        }

        Logger::instance()->log(LogLevel::Debug,
                                QString("MeterModel: 过滤总线ID改变: %1").arg(busId));
    }
}

// 刷新模型数据
void MeterModel::refresh()
{
    updateFilteredMeters();
}

// 根据索引获取电表对象
Meter *MeterModel::getMeterAt(int index) const
{
    if (index < 0 || index >= m_filteredMeters.size())
    {
        return nullptr;
    }

    return m_filteredMeters[index];
}

// 根据电表ID查找索引
int MeterModel::findMeterIndex(int meterId) const
{
    for (int i = 0; i < m_filteredMeters.size(); ++i)
    {
        if (m_filteredMeters[i]->meterId() == meterId)
        {
            return i;
        }
    }

    return -1;
}

// 获取指定索引的电表数据（QML 友好）
QVariantMap MeterModel::getMeterData(int index) const
{
    QVariantMap result;

    if (index < 0 || index >= m_filteredMeters.size())
    {
        return result; // 返回空映射
    }

    Meter *meter = m_filteredMeters[index];
    if (!meter)
    {
        return result;
    }

    // 构建数据映射
    result["meterId"] = meter->meterId();
    result["name"] = meter->name();
    result["location"] = meter->location();
    result["busId"] = meter->busId();
    result["online"] = meter->isOnline();
    result["ua"] = meter->ua();
    result["ub"] = meter->ub();
    result["uc"] = meter->uc();
    result["ia"] = meter->ia();
    result["ib"] = meter->ib();
    result["ic"] = meter->ic();
    result["averageVoltage"] = meter->averageVoltage();
    result["averageCurrent"] = meter->averageCurrent();
    result["totalPower"] = meter->totalPower();
    result["lastUpdateTime"] = meter->lastUpdateTime();
    result["failureCount"] = meter->failureCount();

    return result;
}

// 处理电表数据更新（单个）
void MeterModel::onMeterDataUpdated()
{
    Meter *meter = qobject_cast<Meter *>(sender());
    if (!meter)
    {
        return;
    }

    // 加入待更新队列，延迟批量处理
    m_pendingUpdates.insert(meter->meterId());

    // 启动定时器（如果已在运行，会重新计时）
    if (!m_updateTimer->isActive())
    {
        m_updateTimer->start();
    }
}

// 处理电表数据批量更新（优化后的批量接口）
void MeterModel::onMeterDataBatchUpdated(const QVector<int> &meterIds)
{
    // 批量加入待更新队列
    for (int meterId : meterIds)
    {
        m_pendingUpdates.insert(meterId);
    }

    // 启动定时器（如果已在运行，会重新计时）
    if (!m_updateTimer->isActive())
    {
        m_updateTimer->start();
    }
}

// 处理电表上线
void MeterModel::onDeviceOnline(int meterId)
{
    // 添加到待更新列表，延迟处理（避免大量同时上线时界面卡顿）
    m_pendingUpdates.insert(meterId);

    // 启动定时器（如果已在运行，会重新计时）
    if (!m_updateTimer->isActive())
    {
        m_updateTimer->start();
    }
}

// 处理电表离线
void MeterModel::onDeviceOffline(int meterId)
{
    // 添加到待更新列表，延迟处理（避免大量同时离线时界面卡顿和崩溃）
    m_pendingUpdates.insert(meterId);

    // 启动定时器（如果已在运行，会重新计时）
    if (!m_updateTimer->isActive())
    {
        m_updateTimer->start();
    }
}

// 处理设备总数改变
void MeterModel::onTotalCountChanged()
{
    // 重新加载所有数据
    updateFilteredMeters();
}

// 批量处理待更新的电表
void MeterModel::processPendingUpdates()
{
    if (m_pendingUpdates.isEmpty())
    {
        return;
    }

    Logger::instance()->log(LogLevel::Debug,
                            QString("MeterModel: 批量处理 %1 个电表数据更新").arg(m_pendingUpdates.size()));

    // 如果待更新数量过多（>50个），直接重置整个模型以提高性能
    if (m_pendingUpdates.size() > 50)
    {
        Logger::instance()->log(LogLevel::Info,
                                QString("MeterModel: 大量更新(%1个)，执行整体刷新").arg(m_pendingUpdates.size()));
        m_pendingUpdates.clear();
        updateFilteredMeters();
        return;
    }

    // 批量处理：收集所有需要更新的索引范围
    QVector<int> updateIndices;
    for (int meterId : m_pendingUpdates)
    {
        Meter *meter = m_deviceManager->getMeter(meterId);
        if (!meter)
        {
            continue;
        }

        int index = findMeterIndex(meterId);
        bool shouldShow = matchFilter(meter);

        if (index >= 0 && !shouldShow)
        {
            // 原来显示，现在不显示，需要移除
            beginRemoveRows(QModelIndex(), index, index);
            m_filteredMeters.removeAt(index);
            endRemoveRows();
        }
        else if (index < 0 && shouldShow)
        {
            // 原来不显示，现在显示，需要添加
            beginInsertRows(QModelIndex(), m_filteredMeters.size(), m_filteredMeters.size());
            m_filteredMeters.append(meter);

            // 连接数据更新信号（使用 QueuedConnection 确保在主线程执行）
            connect(meter, &Meter::dataUpdated, this, &MeterModel::onMeterDataUpdated,
                    static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection));

            endInsertRows();
        }
        else if (index >= 0)
        {
            // 仍然显示，记录需要更新的索引
            updateIndices.append(index);
        }
    }

    // 批量发送dataChanged信号（减少UI刷新次数）
    if (!updateIndices.isEmpty())
    {
        // 按索引排序
        std::sort(updateIndices.begin(), updateIndices.end());

        // 合并连续的索引范围，减少信号发送次数
        int rangeStart = updateIndices[0];
        int rangeEnd = updateIndices[0];

        for (int i = 1; i < updateIndices.size(); ++i)
        {
            if (updateIndices[i] == rangeEnd + 1)
            {
                // 连续索引，扩展范围
                rangeEnd = updateIndices[i];
            }
            else
            {
                // 不连续，发送当前范围的信号
                emit dataChanged(createIndex(rangeStart, 0), createIndex(rangeEnd, 0));
                rangeStart = updateIndices[i];
                rangeEnd = updateIndices[i];
            }
        }

        // 发送最后一个范围
        emit dataChanged(createIndex(rangeStart, 0), createIndex(rangeEnd, 0));
    }

    // 发送计数改变信号
    if (!m_pendingUpdates.isEmpty())
    {
        emit countChanged();
    }

    // 清空待更新列表
    m_pendingUpdates.clear();
}

// 更新过滤后的电表列表
void MeterModel::updateFilteredMeters()
{
    beginResetModel();

    // 断开旧的信号连接
    for (Meter *meter : m_filteredMeters)
    {
        disconnect(meter, &Meter::dataUpdated, this, &MeterModel::onMeterDataUpdated);
    }

    m_filteredMeters.clear();

    // 获取所有电表
    QVector<Meter *> allMeters = m_deviceManager->getAllMeters();

    // 根据过滤条件筛选
    for (Meter *meter : allMeters)
    {
        if (matchFilter(meter))
        {
            m_filteredMeters.append(meter);

            // 连接数据更新信号（使用 QueuedConnection 确保在主线程执行）
            connect(meter, &Meter::dataUpdated, this, &MeterModel::onMeterDataUpdated,
                    static_cast<Qt::ConnectionType>(Qt::QueuedConnection | Qt::UniqueConnection));
        }
    }

    endResetModel();
    emit countChanged();

    Logger::instance()->log(LogLevel::Debug,
                            QString("MeterModel: 更新过滤列表，共 %1 条记录").arg(m_filteredMeters.size()));
}

// 检查电表是否符合过滤条件
bool MeterModel::matchFilter(Meter *meter) const
{
    if (!meter)
    {
        return false;
    }

    switch (m_filterMode)
    {
    case ShowAll:
        return true;
    case ShowOnline:
        return meter->isOnline();
    case ShowOffline:
        return !meter->isOnline();
    case ShowByBus:
        return meter->busId() == m_filterBusId;
    default:
        return true;
    }
}
